<template>

  <vab-dialog :fullscreen="fullscreen" :lignCenter="true" :width="dialogWidth" v-model="dialogVisible"
    @close="handleClose" :title="options && options.title ? options.title : '无标题'" :top="options?.top ?? ''">
    <!-- 这里渲染动态加载的组件 -->
    <div class="component-container">
      <component v-model="options" :is="currentComponent" @callBack="handleCallback" />
    </div>
    <template #footer v-if="actions.length > 0">
      <el-button v-for="action of actions" :type="action.type" @click="action.cb">{{ action.label }}</el-button>
    </template>
  </vab-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { defineAsyncComponent } from 'vue';
import AppUtil from "/@/utils/app";
// 定义 Dialog 的状态
const dialogVisible = ref(false);
const currentComponent = ref(null);
const options = ref(null)
const callback = ref(null)
const dialogWidth = ref(null)

const fullscreen = ref(false)
const actions = ref<{ type: "" | "text" | "default" | "success" | "warning" | "info" | "primary" | "danger", label: string, cb: () => void }[]>([])
// 回调函数
const handleCallback = (data) => {
  dialogVisible.value = false;  // 关闭 Dialog

  // 如果提供了回调函数，则执行回调
  if (callback.value && typeof callback.value === 'function') {
    callback.value(data);
  }
};
// 手动加载组件到 Dialog 中
const loadComponent = async (componentPath: string, option: object, cb: Function) => {
  callback.value = cb
  options.value = option
  if (option && option.dialogType == DialogType.Page) {
    dialogWidth.value = '70%'
  } else if (option && option.dialogType == DialogType.QRCode) {
    dialogWidth.value = '280px'
  } else if (option && option.dialogType == DialogType.H5) {
    dialogWidth.value = '450px'
  }

  actions.value = option.actions ?? []
  fullscreen.value = option && option.fullscreen
  // componentPath = componentPath.toLowerCase()
  let componentMap = AppUtil.getComponentMap();
  if (componentMap.has(componentPath)) {
    // 动态加载组件
    let component = componentMap.get(componentPath);
    currentComponent.value = await defineAsyncComponent(component);
    // if (option && option.defaultList) currentComponent.value.merge(option.defaultList)

    dialogVisible.value = true;  // 打开 Dialog
  } else {
    console.log(componentPath + "找不到组件");
  }
};

// 控制 Dialog 的关闭事件
const handleClose = () => {
  // console.log('Dialog 被关闭');
  // 处理 Dialog 关闭的逻辑
};

defineExpose({
  loadComponent,
})

</script>
<style lang="scss" scoped>
::v-deep() {
  .el-dialog:not(.is-fullscreen) .el-dialog__body {
    max-height: 70vh;
    overflow-y: auto;
  }
}

.component-container {
  height: 100%;
  overflow: scroll;
}
</style>
